//
//  LCData.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/28.
//

import Foundation
import LeanCloud
import ZKProgressHUD

var LC = LeanCloudHub()

class LeanCloudHub{
    
    //MARK:User
    
    
    
    //MARK:用户注册√
    func userRegister(username:String,password:String,success: @escaping (()->Void)){
        let emptyStringArray : [String] = []
        let emptyIntArray : [Int] = []
        do {
            let user = LCUser()
            user.username = LCString(username)
            user.password = LCString(password)
            //初始化个人信息表(中间表)
            //收藏表
            let middleTable = LCObject(className: "UserCollection")
            try middleTable.set("user", value: user)
            try middleTable.set("bookIndex", value: emptyIntArray)
            try middleTable.set("collectedTime", value: emptyStringArray)
            //借阅表
            let borrowTable = LCObject(className: "UserBorrow")
            try borrowTable.set("user", value: user)
            try borrowTable.set("bookIndex", value: emptyIntArray)
            try borrowTable.set("borrowTime", value: emptyStringArray)
            
            try user.set("passWord", value: password)
            _ = user.signUp { (result) in
                switch result {
                case .success:
                    _ = middleTable.save()
                    _ = borrowTable.save()
                    success()
                case .failure(error: let error):
                    switch error.code {
                    case 202:
                        ZKProgressHUD.showInfo("用户名已被占用")
                    case 9977:
                        ZKProgressHUD.showInfo("网络连接超时")
                    default:
                        break
                    }
                }
            }
        } catch {
            print(error)
        }
    }
    //MARK:用户登录
    func userLogin(username:String,password:String,success: @escaping (()->Void)){
        _ = LCUser.logIn(username: username, password: password) { result in
            switch result {
            //登录成功
            //  得到user : result
            case .success(object: let user):
                //获取用户信息
                let avatar = user.get("avatar")?.stringValue
                userSelf = User(username: username, avatar: avatar)
                success()
            case .failure(error: let error):
                switch error.code {
                case 210:
                    ZKProgressHUD.showError("密码错误")
                case 211:
                    ZKProgressHUD.showInfo("用户名未注册")
                case 9977:
                    ZKProgressHUD.showInfo("网络连接超时")
                default:
                    break
                }
            }
        }
    }
    //MARK:用户登出
    func userLogout(){
        LCUser.logOut()
    }
    //MARK:用户设置头像
    func userSetAvatar(avatar:String){
        do{
            let user = LCApplication.default.currentUser!
            try user.set("avatar", value: avatar)
            _ = user.save(){ (result) in
                switch result{
                case .success:
                    break
                case .failure(error: let error):
                    print(error)
                }
            }
        } catch {
            print(error)
        }
    }
    //MARK:添加、移除收藏
    func userHandleCollection(book:Book,isCollect:Bool){
        do{
            //拿到user
            let user = LCApplication.default.currentUser!
            //通过user得到中间表
            let collections = LCQuery(className: "UserCollection")
            try collections.where("user", .equalTo(user))
            _ = collections.find(){ (result) in
                switch result{
                case .success(objects: let objects):
                    let collectionObject = objects.first!
                    let bookIndex = LCNumber(integerLiteral: book.index)
                    let bookCollectedTime = LCString(book.collectedTime!)
                    do{
                        switch isCollect {
                        case true:
                            try collectionObject.append("bookIndex", element: bookIndex)
                            try collectionObject.append("collectedTime", element: bookCollectedTime)
                        case false:
                            try collectionObject.remove("bookIndex", element: bookIndex)
                            try collectionObject.remove("collectedTime", element: bookCollectedTime)
                        }
                    } catch {
                        print(error)
                    }
                    _ = collectionObject.save(){ (result) in
                        switch result{
                        case .success:
                            break
                        case .failure(error: let error):
                            print(error)
                        }
                    }
                case .failure(error: let error):
                    print(error)
                }
            }
        } catch {
            print(error)
        }
    }
    //MARK:分享
    func pushToCheckPending(bookName:String,bookFace:Data?,bookAuthor:String,bookAbstract:String){
        let checkPending = LCObject(className: "CheckPending")
        let user = LCApplication.default.currentUser!
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        let time = dateformatter.string(from: Date())
        do{
            try checkPending.set("bookName", value: bookName)
            try checkPending.set("bookAuthor", value: bookAuthor)
            try checkPending.set("bookAbstract", value: bookAbstract)
            try checkPending.set("timeOfApplication", value: time)
            try checkPending.set("user", value: user)
            _ = checkPending.save()
        }catch{
            print(error)
        }
    }
    //MARK:添加、移除借阅
    func userHandleBorrow(book:Book,isBorrow:Bool){
        do{
            //拿到user
            let user = LCApplication.default.currentUser!
            //通过user得到中间表
            let borrows = LCQuery(className: "UserBorrow")
            try borrows.where("user", .equalTo(user))
            _ = borrows.find(){ (result) in
                switch result{
                case .success(objects: let objects):
                    let borrowObject = objects.first!
                    let bookIndex = LCNumber(integerLiteral: book.index)
                    
                    do{
                        switch isBorrow {
                        case true:
                            try borrowObject.append("bookIndex", element: bookIndex)
                            
                        case false:
                            try borrowObject.remove("bookIndex", element: bookIndex)
                            
                        }
                    } catch {
                        print(error)
                    }
                    _ = borrowObject.save(){ (result) in
                        switch result{
                        case .success:
                            break
                        case .failure(error: let error):
                            print(error)
                        }
                    }
                case .failure(error: let error):
                    print(error)
                }
            }
        } catch {
            print(error)
        }
    }
    
    func getUserBookData(){
        let user = LCApplication.default.currentUser!
        getCollections(user: user)
        getShares(user: user)
        getBorrows(user: user)
    }
    //MARK:获取收藏信息
    private func getCollections(user:LCUser){
        //获取收藏信息
        let collections = LCQuery(className: "UserCollection")
        collections.whereKey("user", .equalTo(user))
        _ = collections.find(){ (result) in
            switch result{
            case .success(objects: let objects):
                let object = objects.first!
                let bookCollectedTime = object["collectedTime"]!.arrayValue!
                let bookIndex = object["bookIndex"]!.arrayValue!
                if bookIndex.isEmpty == false{
                    for i in 0...bookIndex.count-1{
                        let bookIndexD = bookIndex[i] as! Double
                        let bookIndex = Int(bookIndexD)
                        //对书库书籍信息进行修改
                        let book = localLibrary.allBook[bookIndex]
                        book.collectedTime = bookCollectedTime[i] as? String
                        book.state.isCollected = true
                        userSelf?.collection.append(book)
                    }
                }
            case .failure(error: let error):
                print(error)
            }
        }
    }
    //MARK:获取分享信息
    private func getShares(user:LCUser){
        let shares = LCQuery(className: "CheckPending")
        shares.whereKey("user", .equalTo(user))
        _ = shares.find(){(result) in
            switch result{
            case .success(objects: let objects):
                for object in objects{
                    let bookName = object["bookName"]?.stringValue
                    let bookAuthor = object["bookAuthor"]?.stringValue
                    let bookAbstract = object["bookAbstract"]?.stringValue
                    let book = Book(face: nil, name: bookName!, author: bookAuthor!, abstract: bookAbstract!)
                    userSelf?.share.append(book)
                }
            case .failure(error: let error):
                print(error)
            }
        }
    }
    //MARK:获取借阅信息
    private func getBorrows(user:LCUser){
        //获取收藏信息
        let collections = LCQuery(className: "UserBorrow")
        collections.whereKey("user", .equalTo(user))
        _ = collections.find(){ (result) in
            switch result{
            case .success(objects: let objects):
                let object = objects.first!
                let bookIndex = object["bookIndex"]!.arrayValue!
                if bookIndex.isEmpty == false{
                    for i in 0...bookIndex.count-1{
                        let bookIndexD = bookIndex[i] as! Double
                        let bookIndex = Int(bookIndexD)
                        //对书库书籍信息进行修改
                        let book = localLibrary.allBook[bookIndex]
                        userSelf?.borrow.append(book)
                    }
                }
            case .failure(error: let error):
                print(error)
            }
        }
    }
    
    
    //MARK:Book
    
    
    
    
    //MARK:SetUpLocalLibrary
    func getLCLibrary(success: @escaping (()->Void)){
        let books = LCQuery(className: "book")
        _ = books.find(){ (result) in
            switch result{
            case .success(objects: let objects):
                var bookSort : [Book] = []
                var indexSort : [Int] = []
                for object in objects{
                    let name = object["name"]!.stringValue!
                    let faceUrl = object["face"]!.stringValue!
                    let author = object["author"]!.stringValue!
                    let abstract = object["abstract"]!.stringValue!
                    let index = object["index"]!.intValue!
                    let faceImage = self.urlToImage(name: faceUrl)
                    let book = Book(face: faceImage, name: name, author: author, abstract: abstract)
                    book.index = index
                    bookSort.append(book)
                }
                for book in bookSort{
                    indexSort.append(book.index)
                }
                //选择排序法
                for _ in bookSort.indices{
                    //为空则停
                    if indexSort.isEmpty == false{
                        let minIndex = indexSort.min()
                        let index = indexSort.firstIndex(of: minIndex!)
                        let book = bookSort[index!]
                        localLibrary.allBook.append(book)
                        bookSort.remove(at: index!)
                        indexSort.remove(at: index!)
                    }
                }
                success()
            case .failure(error: let error):
                print(error)
            }
        }
    }
    
    private func urlToImage(name:String) -> UIImage {
        let image : UIImage!
        image = UIImage(named: name)
        if image != nil{
            return image
        }else{
            return UIImage(named: "Password-hide")!
        }
    }
    
    //MARK:SearchBook
    func searchBook(match:String,success: @escaping (()->Void)){
        let query = LCQuery(className: "book")
        query.whereKey("name", .matchedSubstring(match))
        _ = query.find { result in
            switch result {
            case .success(objects: let comments):
                //数据重构
                for comment in comments {
                    let index = comment.get("index")!.intValue!
                    let book = localLibrary.allBook[index]
                    searchBooks.append(book)
                }
                success()
            case .failure(error: let error):
                print(error)
            }
        }
    }
    
    
}
